from datetime import datetime
from schema.service import Service
import utils.ryu_interface as ryu_if
# from utils.datetime_util import *
import threading


class Flow:
    def __init__(self,src_ip,dst_ip,src_port,dst_port,slice_type,start_datetime, end_datetime, throughput, delay, loss):
        self.src_ip = src_ip
        self.dst_ip = dst_ip
        self.src_port = src_port
        self.dst_port = dst_port
        self.slice_type = slice_type
        self.start_datetime = start_datetime
        self.end_datetime = end_datetime
        self.throughput = throughput
        self.delay = delay
        self.loss = loss


flows = dict()

def add_flow(service:Service):
    up_flow = Flow(service.src_ip,service.dst_ip,0,service.dst_port,service.slice_type,service.start_datetime,service.end_datetime,service.up_throughput,service.delay,service.loss)
    down_flow = Flow(service.dst_ip,service.src_ip,service.dst_port,0,service.slice_type,service.start_datetime,service.end_datetime,service.down_throughput,service.delay,service.loss)
    flows[(service.src_ip, service.dst_ip, 0, service.dst_port)] = up_flow
    flows[(service.dst_ip, service.src_ip, service.dst_port, 0)] = down_flow
    threading.Thread(target=ryu_if.ryu_interface.pre_install_route, args=(vars(up_flow),)).start()
    threading.Thread(target=ryu_if.ryu_interface.pre_install_route, args=(vars(down_flow),)).start()


def get_packetin_flow(l2_src, l2_dst, l3_src_port, l3_dst_port):
    flow  = flows.get((l2_src, l2_dst, 0, l3_dst_port))
    if flow is None:
        flow = flows.get((l2_src, l2_dst, l3_src_port, 0))

    if flow is not None:
        now = datetime.now()
        start_datetime = datetime.strptime(flow.start_datetime,"%Y-%m-%d %H:%M:%S")
        end_datetime = datetime.strptime(flow.end_datetime, "%Y-%m-%d %H:%M:%S")
    
        if now >= start_datetime and now <= end_datetime:
            return flow
        else:
            return None
